package com.cino.users.service.impl;

import com.cino.basic.base.dto.PhoneCodeDto;
import com.cino.basic.base.exception.BusinessException;
import com.cino.basic.util.Md5Utils;
import com.cino.basic.util.StrUtils;
import com.cino.org.domain.Employee;
import com.cino.org.domain.Shop;
import com.cino.users.domain.Logininfo;
import com.cino.users.domain.User;
import com.cino.basic.base.service.impl.BaseServiceImpl;
import com.cino.users.mapper.LogininfoMapper;
import com.cino.users.mapper.UserMapper;
import com.cino.users.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.mockito.internal.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS) //有事务就只有1个
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void phoneRegister(Map<String, String> map) {
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String pwd = map.get("pwd");
        String rePwd = map.get("rePwd");
        //一:校验
        //1.空值
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode)
           ||  StringUtils.isEmpty(pwd) || StringUtils.isEmpty(rePwd) ){
            throw new BusinessException("信息不能为空！");
        }
        //2.两次密码是否一致
        if(!pwd.equals(rePwd)){
            throw new BusinessException("两次密码输入不一致！");
        }
        //3.手机验证码是否过期，是否正确
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if(obj == null){
            throw new BusinessException("手机验证码已过期！");
        }
        //3.1 手机验证码是否正确
        if(!phoneCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("手机验证码错误！");
        }
        //二:添加到数据库
        //当将一个对象转换成另外一个对象的时候，而且代码量大的时候就用obj2Obj
        User user = map2User(map);
        Logininfo logininfo = user2Logininfo(user);
        //1.先添加t_logininfo
        logininfoMapper.save(logininfo);
        //2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    @Override
    @Transactional
    public void emailRegister(Map<String, String> map) throws MessagingException {
        String email = map.get("email");
        String pwd = map.get("pwd");
        String rePwd = map.get("rePwd");

        //一:校验
        //1.空值
        if(StringUtils.isEmpty(email) ||  StringUtils.isEmpty(pwd) || StringUtils.isEmpty(rePwd) ){
            throw new BusinessException("信息不能为空！");
        }
        //2.邮箱号是否已注册过
        if(userMapper.loadByEmail(email)!=null){
            throw new BusinessException("该邮箱号已注册，请直接登录,若忘记密码请联系管理员！");
        }
        //3.两次密码是否一致
        if(!pwd.equals(rePwd)){
            throw new BusinessException("两次密码输入不一致！");
        }
        //二:添加到数据库
        //当将一个对象转换成另外一个对象的时候，而且代码量大的时候就用obj2Obj
        User user = map2User_email(map);
        Logininfo logininfo = user2Logininfo_email(user);
        //1.先添加t_logininfo
        logininfoMapper.save(logininfo);
        //2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

        //三、给用户发送邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("928915144@qq.com");
        helper.setSubject("账号激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
        helper.setText("<h3>你的账号已经注册成功，请<a href='http://127.0.0.1:8080/user/active/"+user.getId()
                +"'>点击这里</a>激活邮件</h3>", true);
        //1.修改状态为待激活
        /*userMapper.updateState(2,user.getId());*/
        helper.setTo(user.getEmail());
        //发送1
        javaMailSender.send(mimeMessage);

    }

    //激活的链接 修改状态
    @Override
    @Transactional
    public void updateState(Long id) {
        User user = userMapper.loadById(id);
        user.setState(3);
        userMapper.update(user);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //根据同名属性原则
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;

    }
    private Logininfo user2Logininfo_email(User user) {
        Logininfo logininfo = new Logininfo();
        //根据同名属性原则
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;

    }

    private User map2User(Map<String, String> map) {
        User user = new User();
        String phone = map.get("phone");
        user.setUsername(phone);
        user.setPhone(phone);
        //生成32位的盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密盐值
        String md5Pwd = Md5Utils.encrypByMd5(salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }
    private User map2User_email(Map<String, String> map) {
        User user = new User();
        String email = map.get("email");
        user.setUsername(email);
        user.setEmail(email);
        //生成32位的盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密盐值
        String md5Pwd = Md5Utils.encrypByMd5(salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(2);
        return user;
    }

//=========== 方法 重构=====================
@Transactional
@Override
public void save(User user) {
    //处理盐值和密码
    String salt = StrUtils.getComplexRandomString(32);
    String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
    user.setSalt(salt);
    user.setPassword(md5Pwd);

    //先添加logininfo
    Logininfo logininfo = new Logininfo();
    BeanUtils.copyProperties(user,logininfo);
    logininfo.setType(0);//管理员
    logininfo.setDisable(true);
    logininfoMapper.save(logininfo);//获取到自增ID

    //添加用户的数据
    user.setLogininfoId(logininfo.getId());
    super.save(user);
}

    @Transactional
    @Override
    public void del(Long id) {
        //先查询登陆信息id
        User user = userMapper.loadById(id);
        //删除logininfo
        logininfoMapper.del(user.getLogininfoId());

        //删除user
        super.del(id);
    }

    @Transactional
    @Override
    public void update(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //查以前的老数据：user里面大的数据来自于前端  -就不会有logininfoId,shop_id
        User oldUser = userMapper.loadById(user.getId());//loginfo_id

        //修改user信息
        user.setLogininfoId(oldUser.getLogininfoId());
        super.update(user);

        //修改登陆信息
        Logininfo oldLogininfo = logininfoMapper.loadById(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }
}
